package cn.bluarry.remeberpass;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private EditText username;
    private EditText passwd;
    private Button login;

    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    private CheckBox rememberpass;



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref= PreferenceManager.getDefaultSharedPreferences(this);
        username=findViewById(R.id.username);
        passwd=findViewById(R.id.pass);
        rememberpass=findViewById(R.id.remember_pass);
        login=findViewById(R.id.login);
        boolean isremember=pref.getBoolean("remember_pass",false);
        if(isremember){
            String acount=pref.getString("username","");
            String passd=pref.getString("password","");
            username.setText(acount);
            passwd.setText(passd);
            rememberpass.setChecked(true);
        }
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(check(username.getText().toString(),passwd.getText().toString())){
                    Toast.makeText(getApplicationContext(),"登录成功",Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent(MainActivity.this,SuccessActivity.class);
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(MainActivity.this,"登录失败,用户名或密码错误",Toast.LENGTH_SHORT).show();
                }
            }
        });


    }

    private boolean check(String username,String password){
        if(username.equals("test")&& password.equals("hehe")){
            editor=pref.edit();
            if(rememberpass.isChecked()){
                editor.putBoolean("remember_pass",true);
                editor.putString("username",username);
                editor.putString("password",password);
            }else{
                editor.clear();
            }
            editor.apply();
            return true;
        }
        return false;
    }
}
